package com.example.hello.controller;

import com.example.hello.common.PageResult;
import com.example.hello.common.Result;
import com.example.hello.entity.Employee;
import com.example.hello.entity.EmployeeExperience;
import com.example.hello.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
public class EmployeeController {

    private static final Logger log = LoggerFactory.getLogger(EmployeeController.class);

    @Autowired
    private EmployeeService employeeService;

    /**
     * 分页查询员工列表
     * @param name 员工姓名（模糊匹配）
     * @param gender 性别（男/女）
     * @param startDate 入职开始日期
     * @param endDate 入职结束日期
     * @param deptId 部门ID
     * @param page 当前页码
     * @param pageSize 每页记录数
     * @return 员工列表结果
     */
    @GetMapping("/emps")
    public Result<PageResult<Employee>> getEmployeeList(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String gender,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            @RequestParam(required = false) Integer deptId,
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        
        PageResult<Employee> pageResult = employeeService.getEmployeeList(
                name, gender, startDate, endDate, deptId, page, pageSize);
        return Result.success(pageResult);
    }

    /**
     * 新增员工
     * @param employee 员工信息（包含工作经历）
     * @return 新增结果
     */
    @PostMapping("/emps")
    public Result<Integer> addEmployee(@RequestBody Employee employee) {
        try {
            Integer id = employeeService.addEmployee(employee);
            return Result.success(id);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 修改员工
     */
    @PutMapping("/emps/{id}")
    public Result<Void> updateEmployee(@PathVariable Integer id, @RequestBody Employee employee) {
        try {
            log.info("更新员工信息: id={}, employee={}", id, employee);
            
            // 设置ID
            employee.setId(id);
            
            boolean success = employeeService.updateEmployee(id, employee);
            if (success) {
                return Result.success();
            } else {
                return Result.error("更新员工失败");
            }
        } catch (IllegalArgumentException e) {
            log.error("更新员工参数错误", e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("更新员工失败", e);
            return Result.error("更新员工失败：" + e.getMessage());
        }
    }

    /**
     * 删除员工
     * @param id 员工ID
     * @return 删除结果
     */
    @DeleteMapping("/emps/{id}")
    public Result<Void> deleteEmployee(@PathVariable Integer id) {
        boolean success = employeeService.deleteEmployee(id);
        if (success) {
            return Result.success();
        } else {
            return Result.error("删除员工失败");
        }
    }

    /**
     * 查询员工详情
     */
    @GetMapping("/emps/{id}")
    public Result<Employee> getEmployeeById(@PathVariable Integer id) {
        try {
            log.info("查询员工详情: id={}", id);
            Employee employee = employeeService.getEmployeeById(id);
            if (employee != null) {
                // 确保敏感信息不返回
                employee.setPassword(null);
                return Result.success(employee);
            } else {
                return Result.error("员工不存在");
            }
        } catch (Exception e) {
            log.error("查询员工详情失败", e);
            return Result.error("查询员工详情失败：" + e.getMessage());
        }
    }

    /**
     * 添加工作经历
     * @param empId 员工ID
     * @param experience 工作经历信息
     * @return 添加结果
     */
    @PostMapping("/emps/{empId}/experiences")
    public Result<Void> addExperience(@PathVariable Integer empId, 
                                    @RequestBody EmployeeExperience experience) {
        boolean success = employeeService.addExperience(empId, experience);
        if (success) {
            return Result.success();
        } else {
            return Result.error("添加工作经历失败");
        }
    }

    /**
     * 删除工作经历
     * @param empId 员工ID
     * @param expId 经历ID
     * @return 删除结果
     */
    @DeleteMapping("/emps/{empId}/experiences/{expId}")
    public Result<Void> deleteExperience(@PathVariable Integer empId, 
                                       @PathVariable Integer expId) {
        boolean success = employeeService.deleteExperience(empId, expId);
        if (success) {
            return Result.success();
        } else {
            return Result.error("删除工作经历失败");
        }
    }

    /**
     * 批量删除员工
     * @param ids 员工ID列表
     * @return 删除结果
     */
    @DeleteMapping("/emps")
    public Result<Void> deleteEmployees(@RequestBody List<Integer> ids) {
        try {
            log.info("接收到批量删除员工请求: ids={}", ids);
            if (ids == null || ids.isEmpty()) {
                return Result.error("请选择要删除的员工");
            }
            
            boolean success = employeeService.deleteEmployees(ids);
            if (success) {
                return Result.success();
            } else {
                return Result.error("批量删除员工失败");
            }
        } catch (Exception e) {
            log.error("批量删除员工失败", e);
            return Result.error("批量删除员工失败：" + e.getMessage());
        }
    }
} 